﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IWS.SiteManager.Core.Model;
using System.Web.Caching;
using System.Web;

namespace IWS.SiteManager.Core
{
	[Serializable]
	public class SettingCache
	{
		/// <summary>
		/// Gets settings for application
		/// </summary>
		public Dictionary<string, Model.Setting> Settings { get; private set; }

		public SettingCache()
		{
		}

		/// <summary>
		/// Gets the current setting cache. Will reload settings if it does not exist in cache.
		/// </summary>
		[System.Xml.Serialization.XmlIgnore]
		public static SettingCache Current
		{
			get
			{
				SettingCache data = null;
				HttpContext context = HttpContext.Current;
				if (context == null)
					throw new ApplicationException("HTTP Context is unavailable when loading settings.");

				Cache cache = context.Cache;
				if (cache == null)
					throw new ApplicationException("Cache unavailable when loading settings.");

				data = cache.Get(Constants.SettingCacheKey) as SettingCache;

				if (data == null)
				{
					data = new SettingCache();
					data.LoadSettings();
					cache.Insert(Constants.SettingCacheKey, data, null, DateTime.Now.AddMinutes(15), Cache.NoSlidingExpiration); //TODO: config needs to go here. 
				}

				return data;
			}
		}

		/// <summary>
		/// Deletes the cache entry.. Next setting retrieval will reload the settings. 
		/// </summary>
		public static void ResetCache()
		{
			HttpContext context = HttpContext.Current;
			if (context == null)
				throw new ApplicationException("HTTP Context is unavailable when clearing settings.");

			Cache cache = context.Cache;
			if (cache == null)
				throw new ApplicationException("Cache unavailable when clearing settings.");

			cache.Remove(Constants.SettingCacheKey);
		}

		private void LoadSettings()
		{
			Model.SiteRepository service = new IWS.SiteManager.Core.Model.SiteRepository();
			Settings = service.GetAllSettings().ToDictionary(o=>o.ID);
		}

		/// <summary>
		/// Gets a setting by its key. 
		/// </summary>
		/// <param name="key">Unique identifier for a setting. Check Constants for key references. </param>
		/// <returns></returns>
		public Setting GetSetting(string key)
		{
			if (Settings.ContainsKey(key))
				return Settings[key];
			else
				throw new SettingNotFoundException("{0} does not exist.", key);
		}
	}
}
